package logic

import (
	"context"
	"database/sql"

	"googee/common/tool"
	"googee/service/user/model"
	"googee/service/user/rpc/internal/svc"
	"googee/service/user/rpc/types/user"

	"github.com/fatih/color"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type RegisterUserByNameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterUserByNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterUserByNameLogic {
	return &RegisterUserByNameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 创建账号
func (l *RegisterUserByNameLogic) RegisterUserByName(in *user.RegisterNameRequest) (*user.UserResponse, error) {
	if in.Name == "" {
		return nil, status.Error(codes.InvalidArgument, "parameter name is empty")
	}

	userinfo, err := l.svcCtx.UserModel.FindOneByName(l.ctx, sql.NullString{String: in.Name, Valid: true})

	if userinfo != nil {
		return nil, status.Errorf(codes.AlreadyExists, "name %s already exists", in.Name)
	}

	color.Red("in.Password=%v", in.Password)
	if in.Password == "" {
		return nil, status.Error(codes.InvalidArgument, "parameter password is empty")
	}

	var usermodel model.User

	usermodel.Name = sql.NullString{String: in.Name, Valid: true}
	usermodel.Password = sql.NullString{String: in.Password, Valid: true}

	nickname := in.GetNickname()
	usermodel.Nickname = sql.NullString{String: nickname, Valid: true}

	if in.Avatar != nil {
		usermodel.Avatar = sql.NullString{String: *in.Avatar, Valid: in.Avatar != nil}
	}

	if in.Gender == nil {
		usermodel.Gender = sql.NullString{String: "N", Valid: true}
	} else {
		gender := in.GetGender()
		if gender != "F" && gender != "M" && gender != "N" {
			return nil, status.Errorf(codes.InvalidArgument, "parameter gender must be 'F', 'M', or 'N', cannot be %s", *in.Gender)
		}
		usermodel.Gender = sql.NullString{String: *in.Gender, Valid: in.Gender != nil}
	}

	//判断插入是否成功
	{
		r, err := l.svcCtx.UserModel.Insert(l.ctx, &usermodel)
		if err != nil {
			return nil, status.Error(codes.Internal, "system error")
		}

		{
			n, err := r.RowsAffected()
			if n <= 0 || err != nil {
				return nil, status.Error(codes.Internal, "system error1")
			}
		}
	}

	//更新邀请码
	dummyusermodel, err := l.svcCtx.UserModel.FindOneByName(l.ctx, sql.NullString{String: in.Name, Valid: true})
	if err != nil {
		return nil, status.Error(codes.Internal, "system error")
	}

	dummyusermodel.Invcode = sql.NullString{String: tool.GetInvCodeByUIDUniqueNew(uint64(dummyusermodel.Id), 6), Valid: true}
	dummyusermodel.Uid = dummyusermodel.Invcode
	l.svcCtx.UserModel.Update(l.ctx, dummyusermodel)

	var resp user.UserResponse
	_ = copier.Copy(&resp, dummyusermodel)
	return &resp, nil
}
